package com.umeox.auto_light

import android.annotation.SuppressLint
import android.graphics.Color
import android.graphics.drawable.GradientDrawable
import android.view.View
import android.widget.LinearLayout
import android.widget.ProgressBar
import android.widget.TextView
import com.umeox.auto_light.DeviceProxy.Companion.STATE_ERROR
import com.umeox.auto_light.DeviceProxy.Companion.STATE_SUCCESS

class DeviceListAdapter : BaseRecyclerViewAdapter<DeviceProxy>() {

    private val deviceList = mutableListOf<DeviceProxy>()

    fun refreshData(list: MutableList<DeviceProxy>) {
        deviceList.clear()
        deviceList.addAll(list)
        notifyDataSetChanged()
    }

    override fun getLayoutId(viewType: Int): Int = R.layout.light_item_device

    override fun getDataByPosition(position: Int): DeviceProxy = deviceList[position]

    override fun getTotalSize(): Int = deviceList.size

    @SuppressLint("SetTextI18n")
    override fun convert(holder: BaseViewHolder, data: DeviceProxy, position: Int) {
        holder.getView<TextView>(R.id.item_index).text = "${position + 1}"
        holder.getView<TextView>(R.id.item_name).text = data.device.name
        holder.getView<TextView>(R.id.item_mac).text = data.device.mac
        (holder.getView<LinearLayout>(R.id.item).background as GradientDrawable).setColor(
            getStateColor(data)
        )
        holder.getView<ProgressBar>(R.id.item_pb).visibility = View.GONE
    }

    private fun getStateColor(data: DeviceProxy): Int {
        return when (data.state) {
            STATE_ERROR -> {
                Color.RED
            }

            STATE_SUCCESS -> {
                Color.GREEN
            }

            else -> {
                Color.WHITE
            }
        }
    }

}